<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品页面</title>
    <!-- 引入Swiper -->
    <link rel="stylesheet" href="https://unpkg.com/swiper@6.8.4/swiper-bundle.min.css">
    <script src="https://unpkg.com/swiper@6.8.4/swiper-bundle.min.js"></script>
    <style>
        .favorite-star {
            font-size: 24px;
            color: #ddd;  /* 默认白色 */
            cursor: pointer;
            transition: color 0.3s;
            margin: 0 10px;
        }

        .favorite-star.active {
            color: #FFD700;  /* 激活状态金色 */
        }

        .favorite-star:disabled {
            cursor: not-allowed;
            opacity: 0.6;
        }
        .jd-product-detail {
            padding: 20px;
            font-family: 'Microsoft YaHei';
        }

        .product-nav {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            border-bottom: 1px solid #eee;
        }

        .main-image {
            height: 600px;
            overflow: hidden;
            position: relative;
        }

        .swiper-slide img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .price-box {
            padding: 20px;
            background: #fff;
            margin: 15px 0;
        }

        .current-price {
            font-size: 2.5em;
            color: #e4393c;
            font-weight: bold;
        }

        .original-price {
            color: #999;
            text-decoration: line-through;
            margin-left: 10px;
        }

        .discount {
            background: #e4393c;
            color: white;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.8em;
            margin-left: 10px;
        }

        .stock-tag {
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.9em;
        }

        .low-stock {
            background: #ffe6e6;
            color: #e4393c;
        }

        .add-cart,.add-favorite,.buy-now {
            background: #e4393c;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 4px;
            margin: 0 10px;
            cursor: pointer;
        }

        .add-cart:disabled,.buy-now:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .quantity-selector {
            display: flex;
            align-items: center;
            gap: 10px;
            margin: 15px 0;
        }
    </style>
</head>

<body>
<div id="app">
    <div class="jd-product-detail" v-if="product">
        <!-- 头部导航 -->
        <nav class="product-nav">
            <span @click="back">返回</span>
            <h2>{{ product.productName }}</h2>
            <span>分享</span>
        </nav>

        <!-- 商品主图区 -->
        <div class="main-image">

                <img :src="product.imageUrl" alt="商品图片">
<!--            <div class="swiper-container" ref="swiperContainer">-->
<!--                <div class="swiper-wrapper">-->
<!--                    <div class="swiper-slide" v-for="(img, index) in product.imageUrl" :key="index">-->
<!--                        <img :src="img.imageUrl" alt="商品图片" >-->
<!--                    </div>-->
<!--                </div>-->
<!--                &lt;!&ndash; 如果需要分页器 &ndash;&gt;-->
<!--                <div class="swiper-pagination"></div>-->
<!--                &lt;!&ndash; 如果需要导航按钮 &ndash;&gt;-->
<!--                <div class="swiper-button-prev"></div>-->
<!--                <div class="swiper-button-next"></div>-->
<!--            </div>-->
        </div>

        <!-- 价格信息 -->
        <div class="price-box">
            <span class="current-price">¥{{ product.price }}</span>
            <span class="original-price" v-if="product.oldPrice">¥{{ product.oldPrice }}</span>
            <span class="discount" v-if="product.discountRate">省{{ product.discountRate }}%</span>
        </div>

        <!-- 库存状态 -->
        <div class="stock-status">
                <span :class="['stock-tag', stockStatusClass]">
                    {{ stockStatusText }}
                </span>
            <span v-if="!product.isPublished" class="unpublished">下架中</span>
        </div>

        <!-- 商品编码 -->
        <div class="product-sn">货号：{{ product.productNumber }}</div>

        <!-- 购买操作区 -->
        <div class="actions">
            <div class="quantity-selector">
                <button @click="decrement" :disabled="quantity <= 1">-</button>
                <input type="number" v-model="quantity" min="1">
                <button @click="increment">+</button>
            </div>
            <div class="action-buttons">
                <button
                        :class="['btn', 'add-cart']"
                        :disabled="!product.isPublished || quantity <= 0"
                        @click="handleAddCart"
                >
                    加入购物车
                </button>
                <span
                        class="favorite-star"
                        :class="{ active: product.isCollected }"
                        @click="toggleFavorite"
                        :disabled="!product.isPublished"
                >★</span>
                <button
                        :class="['btn', 'buy-now']"
                        :disabled="!product.isPublished || quantity <= 0"
                        @click="handleBuyNow"
                >
                    立即购买
                </button>
            </div>
        </div>

        <!-- 商品详情 -->
        <div class="detail-content" v-html="product.description"></div>
    </div>

    <!-- 加载状态 -->
    <div v-else class="loading">加载中...</div>

    <!-- 错误状态 -->
    <div v-if="error" class="error">{{ error }}</div>
</div>
<script src="../js/vue.js"></script>
<script src="../js/element-ui/lib/index.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<link rel="stylesheet" href="../js/element-ui/lib/theme-chalk/index.css">
<script>
    // 创建Vue实例
    new Vue({
        el: '#app',
        data() {
            return {
                userId: 1,
                product: {

                },
                quantity: 1,
                error: null,
                loading: true,
                swiper: null,

            }
        },
        computed: {
            stockStatusText() {
                if (!this.product) return '';
                if (this.product.stock === 0) return '已售罄';
                if (this.product.stock < this.product.stockAlertThreshold) return '库存预警';
                return '充足';
            },
            stockStatusClass() {
                if (!this.product) return '';
                if (this.product.stock === 0) return'sold-out';
                if (this.product.stock < this.product.stockAlertThreshold) return 'low-stock';
                return 'normal';
            }
        },
        methods: {
            setImageHeight() {
                // 图片高度自适应逻辑
            },
            decrement() {
                if (this.quantity > 1) this.quantity--;
            },
            increment() {
                this.quantity++;
            },
            async handleAddCart() {
                try {
                    if (!this.product || !this.product.productId) {
                        this.$message.error('商品信息不完整，无法添加到购物车');
                        return;
                    }

                    // 显示加载状态
                    // this.$message.loading('正在添加到购物车...');
                    const cartItem = {
                        userId: this.userId,
                        productId: this.product.productId,
                        quantity: this.quantity
                    };
                    // 调用后端API
                    const response = await axios.post('/shoppingcarts/add', cartItem);

                    // 处理响应
                    if (response.data.code === 20011) {
                        this.$message.success('添加购物车成功');

                        // 可选：更新购物车数量指示器
                        // this.updateCartCount();

                        // 可选：延迟后关闭消息提示
                        setTimeout(() => {
                            this.$message.close();
                        }, 2000);
                    } else {
                        this.$message.error(response.data.msg || '添加购物车失败');
                    }
                } catch (error) {
                    console.error('添加购物车失败', error);
                    this.$message.error('网络错误，请稍后重试');
                }
            },
            async handleAddFavorite() {
                try {
                    if (!this.product || !this.product.productId) {
                        this.$message.error('商品信息不完整，无法添加到收藏夹');
                        return;
                    }
                    const UFItem = {
                        userId: this.userId,
                        productId: this.product.productId,
                    };
                    const response = await axios.post('/product/add', UFItem);

                    // 处理响应
                    if (response.data.code === 20011) {
                        this.$message.success('添加收藏夹成功');

                        // 可选：更新购物车数量指示器
                        // this.updateCartCount();

                        // 可选：延迟后关闭消息提示
                        setTimeout(() => {
                            this.$message.close();
                        }, 2000);
                    } else {
                        this.$message.error(response.data.msg || '添加收藏夹失败');
                    }
                } catch (error) {
                    console.error('添加收藏夹失败', error);
                    this.$message.error('网络错误，请稍后重试');
                }
            },
            handleBuyNow() {
                console.log('立即购买:', {
                    ...this.product,
                    quantity: this.quantity
                });
                // 实际项目中应该跳转到结算页面
            },
            back() {
                // 返回上一页
                window.history.back();
            },
            initSwiper() {
                console.log('this.$refs.swiperContainer:', this.$refs.swiperContainer);
                // 初始化Swiper
                if (this.$refs.swiperContainer &&!this.swiper) {
                    this.swiper = new Swiper(this.$refs.swiperContainer, {
                        loop: true,
                        autoplay: {
                            delay: 3000
                        },
                        pagination: {
                            el: '.swiper-pagination',
                        },
                        navigation: {
                            nextEl: '.swiper-button-next',
                            prevEl: '.swiper-button-prev',
                        },
                    });
                }
            },
            async toggleFavorite() {
                try {
                    // 发送状态切换请求
                    const response = await axios.post('/product/toggle', {
                        userId: this.userId,
                        productId: this.product.productId
                    }, {
                        headers: {
                            'Content-Type': 'application/json'  // 关键设置
                        }
                    });

                    if (response.data.code === 20011) {
                        // 更新本地状态
                        this.product.isCollected = !this.product.isCollected;
                    }
                } catch (error) {
                    this.$message.error('操作失败，请重试');
                }
            },
            // 初始化时获取收藏状态
            async checkFavoriteStatus() {
                try {
                    const response = await axios.get('/product/check', {
                        params: {
                            userId: this.userId,
                            productId: this.product.productId
                        }
                    },{
                        headers: {
                            'Content-Type': 'application/json'  // 关键设置
                        }
                    });

                    if (response.data.code === 20011) {
                        this.product.isCollected = response.data.data.isCollected;
                    }
                } catch (error) {
                    console.error('获取收藏状态失败:', error);
                }
            },
            mounted() {
                this.checkFavoriteStatus();
            },
        },
        async created() {
            try {
                // 从URL参数获取productId
                const urlParams = new URLSearchParams(window.location.search);
                const productId = urlParams.get('productId');

                if (!productId) {
                    throw new Error('未提供商品ID');
                }

                // 发送GET请求
                const response = await axios.get(`/shoppingcarts/product/${productId}`);
                console.log('response.data.data:', response.data.data);
                this.product = response.data.data;
                console.log('this.product:', this.product);
                this.loading = false;
            } catch (err) {
                console.error('请求出错:', err);
                this.error = err.response?.data?.msg || '网络错误';
                this.loading = false;
            }


        },
        mounted() {
            // 页面加载完成后初始化Swiper
            this.$nextTick(() => {
                this.initSwiper();
            });

        },
        watch: {
            // 监听product变化，重新初始化Swiper
            product() {
                this.$nextTick(() => {
                    this.initSwiper();
                });
            }
        }
    });
</script>
</body>

</html>